package jnpf.engine.custom.xml.impl;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.converter.SequenceFlowXMLConverter;
import org.flowable.bpmn.converter.util.BpmnXMLUtil;
import org.flowable.bpmn.model.BaseElement;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.SequenceFlow;

import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class CustomSequenceFlowXMLConverter extends SequenceFlowXMLConverter {
    protected static final List<ExtensionAttribute> defaultSequenceFlowAttributes = Arrays.asList(
            new ExtensionAttribute(ATTRIBUTE_FLOW_SOURCE_REF ),
            new ExtensionAttribute(ATTRIBUTE_FLOW_TARGET_REF ),
            new ExtensionAttribute(ATTRIBUTE_NAME ),
            new ExtensionAttribute(ATTRIBUTE_FLOW_SKIP_EXPRESSION )
    );
    @Override
    protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
        SequenceFlow sequenceFlow = new SequenceFlow();
    BpmnXMLUtil.addXMLLocation(sequenceFlow, xtr);
        sequenceFlow.setSourceRef(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SOURCE_REF));
        sequenceFlow.setTargetRef(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_TARGET_REF));
        sequenceFlow.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME));
        sequenceFlow.setSkipExpression(xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SKIP_EXPRESSION));
        BpmnXMLUtil.addCustomAttributes(xtr, sequenceFlow, defaultElementAttributes,defaultActivityAttributes,defaultSequenceFlowAttributes);
        parseChildElements(getXMLElementName(), sequenceFlow, model, xtr);

        return sequenceFlow;
    }

    @Override
    protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception {
        SequenceFlow sequenceFlow = (SequenceFlow) element;
        writeDefaultAttribute(ATTRIBUTE_FLOW_SOURCE_REF, sequenceFlow.getSourceRef(), xtw);
        writeDefaultAttribute(ATTRIBUTE_FLOW_TARGET_REF, sequenceFlow.getTargetRef(), xtw);
        if (StringUtils.isNotEmpty(sequenceFlow.getSkipExpression())) {
            writeDefaultAttribute(ATTRIBUTE_FLOW_SKIP_EXPRESSION, sequenceFlow.getSkipExpression(), xtw);
        }
        BpmnXMLUtil.writeCustomAttributes(sequenceFlow.getAttributes().values(), xtw, defaultElementAttributes,
                defaultActivityAttributes,defaultSequenceFlowAttributes);
    }
}
